package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.YddArticle;
import com.itheima.entity.YddUser;
import com.itheima.entity.YddUserData;
import com.itheima.entity.YddUserDto;
import com.itheima.service.ArticleService;
import com.itheima.service.UserDataService;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


//@CrossOrigin
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserDataService userDataService;
    @Autowired
    private ArticleService articleService;


    @GetMapping("/getUserInfo")
    public R<Object> login(HttpServletRequest request) {
        YddUserDto userDto = new YddUserDto();
        //查询到个人信息
        Long token = Long.valueOf(request.getHeader("token"));
        log.info("token-{}", token);
        if (token == null) {
            return R.error("获取用户信息错误", 1000);
        }
        request.getSession().setAttribute("token", token);
        YddUser userServiceOne = userService.getById(token);
        //点赞数
        LambdaQueryWrapper<YddUserData> ylqw = new LambdaQueryWrapper<>();
        ylqw.eq(YddUserData::getUserId, userServiceOne.getId());
        ylqw.eq(YddUserData::getType, 2);
        YddUserData userDataServiceOne = userDataService.getOne(ylqw);

        userDto.setUserInfo(userServiceOne);
        YddArticle articleServiceById = articleService.getById(userDataServiceOne.getArticleId());
        if (null != articleServiceById) {
            if (null != articleServiceById.getClick()) {
                userDto.setZanNum(articleServiceById.getClick());
            }
            //收藏数量
            if (null != articleServiceById.getLovenum()) {
                userDto.setCollectNum(articleServiceById.getLovenum());
            }
            //多少篇文章
            LambdaQueryWrapper<YddArticle> ylqw2 = new LambdaQueryWrapper<>();
            ylqw2.eq(YddArticle::getUserId, token);
            Long count;
            if ((count = Long.valueOf(articleService.count(ylqw2))) != null) {
                userDto.setArticleNum(count);
            }
        }

        return R.success(userDto);
    }
}
